function rest=index(K,N,RNK)

if RNK(1)~=N || size(RNK,2) ~= K
    disp('control index error')
end
old = (0:RNK(K))';
old = old(sum(old,2)<=N,:);
for kk=K-1:-1:1
    new = (0:RNK(kk))';
    newsize=size(new);
    oldsize=size(old,1);
    newones=ones(oldsize,1);
    oldones=ones(newsize);
    right=kron(new,newones);
    left=kron(oldones,old);
    old = [right,left];
    old = unique(old,'rows');
    old = old(sum(old,2)<=N,:);
end
rest=old;



% ref  = RNK+ones(size(RNK));
% rest = zeros(prod(ref,2),K);
% 
% if K==1
%     rest=(0:RNK(K))';
% else
%     rest(:,1)=kron((0:RNK(1))',ones(prod(ref(2:K),2),1));
%     rest(:,K)=kron(ones(prod(ref(1:K-1),2),1),(0:RNK(K))');
%     for kk=2:K-1
%         leftones =ones(prod(ref(1:kk-1),2),1);
%         rightones=ones(prod(ref(kk+1:K),2),1);
%         rest(:,kk)=kron(kron(leftones,(0:RNK(kk))'),rightones);
%     end
% end
% % 
% % 
% % rest(:,K)=kron(ones(cont,1),(0:RNK(K))');
% rest=unique(rest,'rows');
% rest=rest(sum(rest,2)<=N,:);
%     
    